package com.coinread.hr.tools.controller;

import com.coinread.hr.tools.bean.persistence.TablePersistence;
import com.coinread.hr.tools.bean.persistence.UserPersistence;
import com.coinread.hr.tools.service.ExcelService;
import com.coinread.hr.tools.utils.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@Slf4j
@RequestMapping("excel")
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    @Autowired
    private UserPersistence userPersistence;

    @Autowired
    private TablePersistence tablePersistence;

    @RequestMapping("")
    public ModelAndView init(){
        return new ModelAndView("excel");
    }

    @RequestMapping(value = "read",method = RequestMethod.POST)
    public ModelAndView read(@RequestPart("file") MultipartFile file){
        String fileName = file.getOriginalFilename();
        if (!ToolUtils.isExcel(fileName)){
            ModelAndView model = new ModelAndView("alert");
            model.addObject("message","请上传正确的文件格式");
            return model;
        }
        excelService.setNull();
        log.info("读取文件成功！ 文件名称：{} ",fileName);
        excelService.getList(file);
        ModelAndView modelAndView = new ModelAndView("redirect:/excel/table");
        return modelAndView;
    }

    @RequestMapping("table")
    public ModelAndView table(){
        ModelAndView modelAndView = new ModelAndView("table");
        modelAndView.addObject("list",userPersistence.getInfo());
        modelAndView.addObject("column",tablePersistence.getTableNameList());
        return modelAndView;
    }

    @RequestMapping("clear")
    public ModelAndView clear(){
        excelService.setNull();
        log.info("清空列表");
        ModelAndView model = new ModelAndView("alert");
        model.addObject("message","已清除列表");
        return model;
    }
}
